package com.example.cunion.webSocket;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.example.cunion.exception.CunionException;
import com.example.cunion.mapper.ChatMapper;
import com.example.cunion.util.MarkdownUtil;
import com.example.cunion.util.SpringContextHolder;
import org.commonmark.node.Node;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.html.HtmlRenderer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;


//@Component
@ServerEndpoint("/websocket/{onlineUser}")
public class WebSocketServerEndpoint {


    private static final ChatMapper chatMapper = SpringContextHolder.getBean(ChatMapper.class);


    private static final Logger logger = LoggerFactory.getLogger(WebSocketServerEndpoint.class);

    /**
     * 所有在线用户的Session
     */
    private static final Set<Session> onlineUsers = Collections.synchronizedSet(new HashSet<Session>());


    @OnOpen
    public void onOpen(Session session, @PathParam("onlineUser") String onlineUser) {
        logger.info("WebSocket连接成功，用户{}", onlineUser);
        onlineUsers.add(session);

        // 给用户发送未读消息
//        List<TbChatmsg> chatMsgs = chatmsgDao.selectUnreadMsgByUser(onlineUser);
//        System.out.println("chatmsgDao ====> " + chatmsgDao);
//        for (TbChatmsg chatMsg : chatMsgs) {
//            JSONObject json = new JSONObject();
//            json.put("id", chatMsg.getId());
//            json.put("from", chatMsg.getFrom());
//            json.put("to", chatMsg.getTo());
//            json.put("content", chatMsg.getContent());
//            json.put("sendTime", chatMsg.getSendTime().getTime());
//
//            session.getAsyncRemote().sendText(chatMsg.getContent());
//
//            // 标记为已读
//            chatMsg.setStatus(1);
//            chatmsgDao.updateByPrimaryKey(chatMsg);
//        }
    }


//    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        logger.info("接收到一条消息：{}", message);
        JSONObject bean = JSONUtil.toBean(message, JSONObject.class);
        String to = bean.get("receiverId").toString();
        Session targetSession = getSessionByUser(to);
        if (targetSession != null) {
            String content = bean.get("content").toString();
            MarkdownUtil markdownUtil = new MarkdownUtil();
            String result = markdownUtil.convertToMarkdown(content);
            targetSession.getAsyncRemote().sendText(result);
            //修改消息已读状态
            if (bean.containsKey("id")){
                String id = bean.get("id").toString();
                Integer result1 = chatMapper.updateStatus(id);
                if (result1 != 1){
                    throw new CunionException("修改信息状态失败！");
                }
            }
        }
    }

    /**
     * 根据用户ID查找对应的Session
     */
    private Session getSessionByUser(String user) {
        for (Session session : onlineUsers) {
            if (user.equals(session.getPathParameters().get("onlineUser"))) {
                return session;
            }
        }
        return null;
    }


    @OnClose
    public void onClose(Session session, @PathParam("onlineUser") String onlineUser) {
        logger.info("WebSocket连接关闭，用户{}", onlineUser);
        onlineUsers.remove(session);
    }

    @OnError
    public void onError(Throwable throwable, Session session) {
        logger.error("WebSocket发生错误", throwable);
        onlineUsers.remove(session);
        try {
            session.close();
        } catch (IOException e) {
            logger.error("关闭WebSocket Session失败", e);
        }
    }

    /**
     * 将消息存储到数据库中
     */
    private String saveMessage(String from, String from_name, String to, String to_name, String content) {

        return null;
    }




}
